
import 'dart:convert';

import 'DBDataType.dart';

class DBScheme {
  DBScheme({ 
    this.mapName,
    required this.columnName,
    required this.columnType,
    this.isNull = true,
    this.isPrimaryKey = false,
    this.autoIncrement = false,
    this.sinceFrom = 1
  });
  // 字典名称
  String? mapName;
  // 列名
  String columnName;
  // 列的类型
  DBDataType columnType;
  // 是否为null
  bool isNull;
  // 是否否是主键
  bool isPrimaryKey;
  // 是否自增
  bool autoIncrement;
  // 自从哪个版本开始启用
  int sinceFrom;

  String get type {
    switch (columnType) {
      case DBDataType.TEXT: return "text";
      case DBDataType.BLOB: return "blob";
      case DBDataType.INTEGER: return "integer";
      case DBDataType.REAL: return "real";
      case DBDataType.BOOL: return "integer";
      case DBDataType.MAP: return 'text';
      case DBDataType.List: return 'text';
      default: return "";
    }
  }

  String get column {
    String nullStr = isNull ? "" : " not null ";
    String primaryStr = isPrimaryKey ? " primary key ": "";
    String autoStr = autoIncrement ? " autoincrement " : "";
    return "$columnName $type$nullStr$primaryStr$autoStr";
  }

  String addColumn(String table) {
    return "ALTER TABLE $table ADD COLUMN $column";
  }

  Map<String,dynamic> decode(Map<String,dynamic> origin) {
    String mapKey = mapName ?? columnName;
    var value = origin[columnName];
    if(value != null) {
      if(columnType == DBDataType.MAP || columnType == DBDataType.List) {
        value = json.decode(value);
      }
      if(columnType == DBDataType.BOOL){
        value = value == 1 ? true : false;
      }
    }

    return {
      mapKey: value,
    };
  }

  Map<String,dynamic> convert(Map<String,dynamic> target) {
    var value = target[mapName ?? columnName];
    if(value is Map || value is List) {
      value = json.encode(value);
    }
    if(value is bool) {
      value = value ? 1 : 0;
    }
    return {
      columnName: value,
    };
  }
}